package com.java.framework.utils;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.google.common.collect.Lists;

/**
 * 逻辑条件表达式 用于复杂条件时使用，如多属性对应值的OR查询等
 * @author sunshine
 *
 * @param <T>
 */
public class LogicalExpression<T> implements Criterion<T> {
	
	private Criterion<T>[] criterions;	// 逻辑表达式中包含的表达式
    private Logical logical;	//计算符
    
    public LogicalExpression(Criterion<T>[] criterions, Logical logical) {
        this.criterions = criterions;
        this.logical = logical;
    }

	@Override
	public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
		// TODO Auto-generated method stub
		List<Predicate> predicates = Lists.newArrayList();
		for (Criterion<T> criterion : criterions) {
			predicates.add(criterion.toPredicate(root, query, cb));
		}
		switch(logical){
		case OR:
			return cb.or(predicates.toArray(new Predicate[predicates.size()]));
		case AND:
			return cb.and(predicates.toArray(new Predicate[predicates.size()]));
		default:
			return cb.and(predicates.toArray(new Predicate[predicates.size()]));
		}
	}

}
